<template>
  <div id="userRegisterView">
    <h2 style="margin-bottom: 16px">用户注册</h2>
    <a-form
      style="max-width: 480px; margin: 0 auto"
      label-align="left"
      auto-label-width
      :model="form"
      :rules="rules"
      @submit="handleSubmit"
    >
      <a-form-item field="userAccount" label="用户名" validate-trigger="blur">
        <a-input v-model="form.userAccount" placeholder="请输入用户名" />
      </a-form-item>
      <a-form-item field="userPassword" label="密码" validate-trigger="blur">
        <a-input-password
          v-model="form.userPassword"
          placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item
        field="checkPassword"
        label="确认密码"
        validate-trigger="blur"
      >
        <a-input-password
          v-model="form.checkPassword"
          placeholder="确认输入密码"
        />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit" style="width: 120px">
            注册
          </a-button>
          <a-button html-type="submit" style="width: 120px" @click="toLogin">
            返回登录
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { UserControllerService, UserRegisterRequest } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";

/**
 * 表单信息
 * checkPassword?: string;
 * userAccount?: string;
 * userPassword?: string;
 */
const form = reactive({
  checkPassword: "",
  userAccount: "",
  userPassword: "",
} as UserRegisterRequest);

const router = useRouter();

/**
 * 返回登录，跳转到登录页面
 */
const toLogin = () => {
  router.push({
    path: "/user/login",
  });
};

/**
 * 提交表单
 * @param data
 */
const handleSubmit = async () => {
  const res = await UserControllerService.userRegisterUsingPost(form);
  // 注册成功，跳转到登录页
  if (res.code === 0) {
    message.success("注册成功，即将前往登录页面");
    setTimeout(() => {
      router.push({
        path: "/user/login",
        replace: true,
      });
    }, 1000);
  } else {
    message.error("注册失败，" + res.message);
  }
};

const rules = {
  userAccount: [
    {
      required: true,
      message: "用户名是必填项",
    },
  ],
  userPassword: [
    {
      required: true,
      message: "密码是必填项",
    },
  ],
  checkPassword: [
    {
      required: true,
      message: "确认密码是必填项",
    },
    {
      validator: (rule: any, value: string) => {
        if (value !== form.userPassword) {
          return Promise.reject("两次输入的密码不一致");
        }
        return Promise.resolve();
      },
    },
  ],
};
</script>
